package pe.hongi.frist;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import net.daum.adam.publisher.AdView;
import net.daum.adam.publisher.AdView.AnimationType;
import net.daum.adam.publisher.AdView.OnAdClickedListener;
import net.daum.adam.publisher.AdView.OnAdClosedListener;
import net.daum.adam.publisher.AdView.OnAdFailedListener;
import net.daum.adam.publisher.AdView.OnAdLoadedListener;
import net.daum.adam.publisher.AdView.OnAdWillLoadListener;
import net.daum.adam.publisher.impl.AdError;


import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.JsPromptResult;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;



public class credu_replay extends Activity {
    /** Called when the activity is first created. */
	
	WebView webview;
	String one="";
	String two="";
	Handler		mHandler;
	String path1,  path2, down_url_id;
	Button down_progress_btn;
	ProgressBar progress;
	LinearLayout down_progress, progress_pop_bg2;
	DownloadThread thread;
	SavePdf_DBAdapter save_pdf;
	
	private static final String LOGTAG = "BannerTypeJava";
	private RelativeLayout relativeLayout = null;
	private AdView adView = null;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
//        save_pdf = new SavePdf_DBAdapter(this);
//        save_pdf.open();
        
        webview=(WebView)findViewById(R.id.webview);
        
		Bundle extras = getIntent().getExtras();         
	    if(extras!=null){
	    	if(extras.getString("off_url")!=null){
	    		         
	    	String off_url=extras.getString("off_url");
	    	
	        webview.loadUrl(off_url);
	    	
	    	}
	    }else{
	    	
	        webview.loadUrl("http://m.slrclub.com/");
	     	
	    }
        webview.getSettings().setJavaScriptEnabled(true);
		
        webview.setWebViewClient(new MYWebViewClient());
		showweb();
		
		relativeLayout = new RelativeLayout(this);
		// Ad@m 광고 뷰 생성 및 설정
		adView = new AdView(this);

		// 광고 클릭시 실행할 리스너
		adView.setOnAdClickedListener(new OnAdClickedListener() {
			
			@Override
			public void OnAdClicked() {
				Log.i(LOGTAG, "광고를 클릭했습니다.");
			}
		});
		
		// 광고 내려받기 실패했을 경우에 실행할 리스너
		adView.setOnAdFailedListener(new OnAdFailedListener() {
			@Override
			public void OnAdFailed(AdError arg0, String arg1) {
			Log.w(LOGTAG, arg1);
			}
		});
		// 광고를 정상적으로 내려받았을 경우에 실행할 리스너
		adView.setOnAdLoadedListener(new OnAdLoadedListener() {
			@Override
			public void OnAdLoaded() {
			Log.i(LOGTAG, "광고가 정상적으로 로딩되었습니다.");
			}
		});
		// 광고를 불러올때 실행할 리스너
		adView.setOnAdWillLoadListener(new OnAdWillLoadListener() {
			@Override
			public void OnAdWillLoad(String arg1) {
			Log.i(LOGTAG, "광고를 불러옵니다. : " + arg1);
			}
		});
		// 광고를 닫았을때 실행할 리스너
		adView.setOnAdClosedListener(new OnAdClosedListener() {
			@Override
			public void OnAdClosed() {
				Log.i(LOGTAG, "광고를 닫았습니다.");
			}
		});
		
		// 할당 받은 clientId 설정
		adView.setClientId("28b0Z0GT136c8518142");
		// 광고 갱싞 시간 : 기본 60초
		adView.setRequestInterval(60);
		// Animation 효과 : 기본 값은 AnimationType.NONE
		adView.setAnimationType(AnimationType.FLIP_HORIZONTAL);
		adView.setVisibility(View.VISIBLE);
}
@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		
		if(adView != null){
			adView.destroy();
			adView = null;
		}
//		save_pdf.close();
		
	}
public class MYWebViewClient extends WebViewClient{
		
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			// TODO Auto-generated method stub
			
			webview.loadUrl(url);
			
			return super.shouldOverrideUrlLoading(view, url);
		}
		
		@Override
		public void onPageFinished(WebView view, String url) {
			// TODO Auto-generated method stub
			

			  Log.d("vvv","url=="+url); 	 
//				url.toLowerCase(); 소문자
//              url.toUpperCase(); 대문자

			
			if(url.indexOf(".mp4") != -1){
			
			 if(one.equals(url)){
				 one=""; 
				 return;	
			 }
				
				one=url;
		 	
			 	Intent t=new Intent(credu_replay.this, mediaplayer.class);
			    t.putExtra("media_url", url);
			    startActivity(t);
		 	    
			}
			if(url.indexOf(".pdf")!=-1){
				

				  Log.d("Tag",".pdf"); 	 
				
				 if(two.equals(url)){
					 two=""; 
					 return;	
				 }
				 
				 two=url;
				 
				 downloadFile(url);
				 
			}
			if(url.indexOf(".png")!=-1){
				
				Intent t =new Intent(credu_replay.this, ImageWebView.class);
				t.putExtra("image_url", url);
				startActivity(t);
				
			}
			if(url.indexOf(".jpg")!=-1){
				
				Intent t =new Intent(credu_replay.this, ImageWebView.class);
				t.putExtra("image_url", url);
				startActivity(t);
			}
			
			if(url.indexOf(".bmp")!=-1){
				
				Intent t =new Intent(credu_replay.this, ImageWebView.class);
				t.putExtra("image_url", url);
				startActivity(t);
			}
			
			
			
		super.onPageFinished(view, url);
			
		}
		
		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
		
			
			super.onPageStarted(view, url, favicon);
		}
	}

	public void showweb(){
	   
	  
		webview.getSettings().setPluginsEnabled(true);
		webview.getSettings().setJavaScriptEnabled(true);  //javascript ��� �����ϰ� �Ѵ�
		
		webview.addJavascriptInterface(new AndroidBridge(), "android");
		
		final Context myApp = this;
		webview.setWebChromeClient(new WebChromeClient() {
		    @Override
		    public boolean onJsAlert(WebView view, String url, String message, final android.webkit.JsResult result)
		    {
		        new AlertDialog.Builder(myApp)
		            .setTitle("AlertDialog")
		            .setMessage(message)
		            .setPositiveButton(android.R.string.ok,
		                    new AlertDialog.OnClickListener()
		                    {
		                        public void onClick(DialogInterface dialog, int which)
		                        {
		                            result.confirm();
		                        }
		                    })
		            .setCancelable(false)
		            .create()
		            .show();
		        result.confirm();
		        return true;
		    };
		    
		    @Override
		    public boolean onJsPrompt(WebView view, String url, String message,
		    		String defaultValue, JsPromptResult result) {
		    	// TODO Auto-generated method stub
		    
		    
	    	return super.onJsPrompt(view, url, message, defaultValue, result);
	    	
		    }
		    
	   });
    }
	 public class AndroidBridge{
		   
		   public void callAndroid(final String arg){
			   
			Handler handler=new Handler();
			handler.post(new Runnable(){

				public void run() {
					// TODO Auto-generated method stub
					   Log.v("Tag","callAndroid("+arg+")");
					   webview.loadUrl("http://m.imba.ac.kr/imba/servlet/controller.mobile.main.MainServlet?p_process=mainPage");
				   }
			   });
			   
		   }
		   
	   }
	 
	 public void downloadFile(final String down_url){

		
		 String arry[] = down_url.split("/");
		 
		 Log.d("Tag",".arry[7]=="+arry[7]); 	 
		 
		 final String path_id=arry[7];
		 
		 
		 if(save_pdf.countEntry_for_pdf_id(path_id)!=0){
			 
			 Cursor sor=save_pdf.getEntry_for_pdf_id(path_id);
			 
			  String db_path=sor.getString(sor.getColumnIndexOrThrow("path"));
			  
			  File dir3 = new File(db_path);
				if(dir3.exists()) {
					
					  Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
					  intent.addCategory(intent.CATEGORY_DEFAULT);
					  intent.setDataAndType(Uri.fromFile(new File(db_path)), "application/pdf");
					  startActivity(intent);
					  return;
				}
			  
		 }
		 
		 
			path1 = android.os.Environment.getExternalStorageDirectory()+"/imba";

			try {
				File dir = new File(path1);

				if(!dir.exists()) {
					dir.mkdirs();
				}
			}catch (Exception e) {
				// TODO: handle exception
			}

			path2 = path1+"/"+path_id;

			
			
		 
		 
		 
//		 progress_pop_bg2 =(LinearLayout)findViewById(R.id.progress_pop_bg2);
//		 down_progress=(LinearLayout)findViewById(R.id.down_progress);
//		 progress=(ProgressBar)findViewById(R.id.progress);
//		 progress.setProgress(0);
//		 
//		 down_progress_btn=(Button)findViewById(R.id.down_progress_btn);
//		 
//		 down_progress.setVisibility(View.VISIBLE);
//		 progress_pop_bg2.setVisibility(View.VISIBLE);
//		 
//		 progress_pop_bg2.setOnClickListener(new OnClickListener() {
//			@Override
//			public void onClick(View v) {
//				// TODO Auto-generated method stub
//				
//				   Log.d("Tag","click"); 	 
//				
//			}
//		});
		 

			mHandler = new Handler() {
				public void handleMessage(Message msg) {
					if(msg.what == 0) 
					{
						//다운로드 준비
						progress.setProgress(0);

					}
					else if(msg.what == 1) 
					{

						//다운로드 완료
						 progress.setProgress(progress.getMax());
						
						 save_pdf.insertEntry(down_url, path2, path_id);
						 
						 Handler mmHandler=new Handler();
							Runnable r=new Runnable(){
								public void run(){

									 
									 progress_pop_bg2.setVisibility(View.GONE);
									 down_progress.setVisibility(View.GONE);
									 
									  
									   Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
									   intent.addCategory(intent.CATEGORY_DEFAULT);
									   intent.setDataAndType(Uri.fromFile(new File(path2)), "application/pdf");
									   startActivity(intent);

								}
							};
							mmHandler.postDelayed(r,1000);
					
						 
						
						
					}
					else if(msg.what == 2) 
					{
						
					}
					else if(msg.what == 3) 
					{

					}
					else if(msg.what == 4) 
					{   
						//fail
						
						 progress_pop_bg2.setVisibility(View.GONE);
						 down_progress.setVisibility(View.GONE);

					}
					else if(msg.what == 1024)
					{
						progress.setProgress(progress.getProgress() + (1024*100)); //progress bar 갱신
					}
				}
			};

			//다운로드 취소 버튼
			
			down_progress_btn.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub

					 progress_pop_bg2.setVisibility(View.GONE);
					 down_progress.setVisibility(View.GONE);
					
					String total =path2;
					try{

						thread.sleep(1000);
						thread.interrupt();

						File file=new File(total);
						file.delete();

						
					}catch (Exception e) {

					}

				}
			});


			Handler mmHandler=new Handler();
			Runnable r=new Runnable(){
				public void run(){

					Log.d("Tag",".start"); 
					
					thread = new DownloadThread();
					thread.progress_downlord(path2, down_url);	
					thread.start();

				}
			};
			mmHandler.postDelayed(r,1000);


		}


		class DownloadThread extends Thread 
		{
			String URL = "";
			String PATH = "";

			public void progress_downlord(String  path, String down_url){

	         
				//다운로드 시작
				
				URL=down_url;
				PATH=path;
			} 


			public void run() { 

				
				 Log.d("Tag",".run"); 	 
					
				
				try {

					URL url = new URL(URL);
					HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();   
					urlConnection.setRequestMethod("GET");   
					urlConnection.setDoOutput(true);   
					urlConnection.connect();

					InputStream is = urlConnection.getInputStream();

					progress.setMax(urlConnection.getContentLength());
					mHandler.sendEmptyMessage(0);

					 Log.d("Tag",".run1"); 	 
						
						

					File file = new File(PATH);
					file.createNewFile();
					FileOutputStream fos = new FileOutputStream(file);
					
					 Log.d("Tag",".run2"); 	 
						
						
					
					writeFile(is, fos);
					fos.close();
					urlConnection.disconnect();

				} catch (Exception e) {
					 Log.d("Tag",".e-="+e); 	 
					 mHandler.sendEmptyMessage(4);

						
				}
			}

			public void writeFile(InputStream is, OutputStream os) throws IOException
			{
				 Log.d("Tag",".writeFile"); 	 
					
				
				int c = 0;
				int Counter = 0;
				byte [] buffer = new byte[1024];
				while((c = is.read(buffer, 0, 1024)) != -1) {
					os.write(buffer, 0, c);

					Counter++;
					if (Counter >= 100) {
						Counter = 0;
						
						
						mHandler.sendEmptyMessage(1024);
					}
				}
				os.flush();
				
				 Log.d("Tag",".sendEmptyMessage1"); 	 
				mHandler.sendEmptyMessage(1);

			}		

		}

	@Override
	public void onBackPressed()
	{
		if (webview.canGoBack())
		{
			webview.goBack();
		}
		else
		{
			finish();
		}
	}
}